package me.leiusual.sharing.ui.product.dialog

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations.switchMap
import androidx.lifecycle.ViewModel
import me.leiusual.sharing.api.model.ProductDetail
import me.leiusual.sharing.pref.Token
import me.leiusual.sharing.repository.CartRepository
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.util.extension.toLiveData
import javax.inject.Inject

/**
 * author: leiusual
 * create on: 2019-07-27
 * description:
 */
class ProductOptionalViewModel @Inject constructor(
    private val cartRepository: CartRepository,
    val token: Token
) : ViewModel() {

  // 当前Sku

  private val _productSku = MutableLiveData<ProductDetail.Sku>()
  val productSku: LiveData<ProductDetail.Sku> = _productSku
  fun productSku(sku: ProductDetail.Sku) {
    _productSku.value = sku
  }

  // 当前Mia

  private val _productMia = MutableLiveData<ProductDetail.Mia>()
  val productMia: LiveData<ProductDetail.Mia> = _productMia
  fun productMia(mia: ProductDetail.Mia) {
    _productMia.value = mia
  }

  // 加入购物车

  private val _cartAdd = MutableLiveData<ParamsCartAdd>()
  val cartAdd: LiveData<Data<Unit>> = switchMap(_cartAdd) {
    cartRepository.cartAdd(it.mia, it.quantity, it.r).toLiveData()
  }

  fun cartAdd(miaId: Long, quantity: Int, r: Long?) {
    _cartAdd.value = ParamsCartAdd(miaId, quantity, r)
  }

  data class ParamsCartAdd(val mia: Long, val quantity: Int, val r: Long?)
}